package com.example.goodpet.activity.adapter;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.goodpet.R;
import com.example.goodpet.common.SpZoomImageView;
import com.example.goodpet.utils.Constants;
import com.example.goodpet.utils.UIUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class PetInfoImageAdapter extends RecyclerView.Adapter<PetInfoImageAdapter.ViewHolder>{
    private static final String TAG = "test";
    private List<String> petImage;
    private Context context;

    private Dialog dialog;
    //private ImageView mImageView;
    private SpZoomImageView mImageView;
    private ViewGroup.LayoutParams param;
    private int heightPixels;
    private int widthPixels;

    public PetInfoImageAdapter(List<String> petImage,Context context) {
        this.petImage = petImage;
        this.context=context;
    }

    @NonNull
    @Override
    public PetInfoImageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_recycler_image_400dp, parent, false);
        return new ViewHolder(inflate);
    }

    @Override
    public void onBindViewHolder(@NonNull PetInfoImageAdapter.ViewHolder holder, int position) {
        //加载图片
        Glide.with(UIUtils.getContext()).load(Constants.BASE_URL_IMAGE+petImage.get(position)).into(new CustomTarget<Drawable>() {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                holder.image.setImageDrawable(resource);
                init(holder);
                initListener(holder);
            }

            @Override
            public void onLoadCleared(@Nullable Drawable placeholder) {

            }
        });

    }
    /**
     * 初始化dialog
     */
    private void init(PetInfoImageAdapter.ViewHolder holder){
        //大图所依附的dialog
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        widthPixels = displayMetrics.widthPixels;
        heightPixels = displayMetrics.heightPixels;
        param=new ViewGroup.LayoutParams(widthPixels,heightPixels);
        dialog = new Dialog(context,R.style.myDialog_style);
        mImageView = getImageView(holder);
        //dialog.addContentView();
        dialog.setContentView(mImageView,param);
    }

    /**
     * 获取image的内容
     * @return
     */
    private SpZoomImageView getImageView(PetInfoImageAdapter.ViewHolder holder){

        SpZoomImageView iv=new SpZoomImageView(context);

        //ImageView iv = new ImageView(context);
        //iv.setScaleType(ImageView.ScaleType.FIT_XY);
        //iv.setLayoutParams(new ViewGroup.LayoutParams(widthPixels,heightPixels));
        //iv.setLayoutParams(param);
        iv.setPadding(0,0,0,0);

        Bitmap bitmap1 = ((BitmapDrawable) holder.image.getDrawable()).getBitmap();

        Bitmap bitmap = UIUtils.zoomImg(bitmap1,widthPixels,Math.min(bitmap1.getHeight()*2,heightPixels/2) );

        iv.setImageBitmap(bitmap);
        return iv;
    }
    private void initListener(PetInfoImageAdapter.ViewHolder holder){
        holder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();
            }
        });
        //大图的点击事件（点击让他消失）
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        //大图的长按监听
        mImageView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                //弹出的“保存图片”的Dialog
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setItems(new String[]{"保存图片"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        saveCroppedImage(((BitmapDrawable) mImageView.getDrawable()).getBitmap());
                    }
                });
                builder.show();
                return true;
            }
        });
    }

    /**
     * 保存照片
     * @param bitmap
     */
    private void saveCroppedImage(Bitmap bitmap){
        File fileDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        String filename=System.currentTimeMillis()+".jpeg";
        File file = new File(fileDir.getPath() + "/" + filename);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG,50,fos);
            fos.close();
            //把图片插入到相册
            MediaStore.Images.Media.insertImage(context.getContentResolver(),file.getAbsolutePath(),file.getName(),null);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public int getItemCount() {
        return petImage.size();
    }
    class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView image;
        private ImageView delete;


        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            image = itemView.findViewById(R.id.image);
            delete = itemView.findViewById(R.id.deleteImage);
            delete.setVisibility(View.GONE);

        }
    }

}
